package com.elite;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.axis.message.MessageElement;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;



public class MYSMS implements Runnable{
	private static final Log log=LogFactory.getLog(FileFTP.class);
	public static com.elite.FtpBean ftpbean;
	public static String times;
	private boolean flag = true; 
	private static int Hz =30; 
	private static String sql =" select * from Documentout where DOCTYPE=3 and ((Status=0) or (Status!=1 and TrialCount<TrialCountLimit)) "; 
	private static String update_sql="";
	public static String username;
	public static String username1;
	public static String password;
	public static String password1;
	public static String XHH;
	public static String XHH1;
	private static String LastTryDateTime="";
	private static String FinishDateTime="";
	private static SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
	
	

    public static com.elite.FtpBean getFtpbean() {
		return ftpbean;
	}
	public static void setFtpbean(com.elite.FtpBean ftpbean) {
		MYSMS.ftpbean = ftpbean;
	}
	public static String getTimes() {
		return times;
	}
	public static void setTimes(String times) {
		MYSMS.times = times;
	}
	public static String getUsername() {
		return username;
	}
	public static void setUsername(String username) {
		MYSMS.username = username;
	}
	public static String getUsername1() {
		return username1;
	}
	public static void setUsername1(String username1) {
		MYSMS.username1 = username1;
	}
	public static String getPassword() {
		return password;
	}
	public static void setPassword(String password) {
		MYSMS.password = password;
	}
	public static String getPassword1() {
		return password1;
	}
	public static void setPassword1(String password1) {
		MYSMS.password1 = password1;
	}
	public static String getXHH() {
		return XHH;
	}
	public static void setXHH(String xhh) {
		XHH = xhh;
	}
	public static String getXHH1() {
		return XHH1;
	}
	public static void setXHH1(String xhh1) {
		XHH1 = xhh1;
	}
	public static String getdesc(String a){
    	if(a.equals("-1")){
    		return "发送失败--检查是否有余额";
    	}else if(a.equals("-2")){
    		return "参数错误--看参数传的是否均正常,请调试程序查看各参数";
    	}else if(a.equals("-3")){
    		return "序列号密码不正确--1.序列号未注册2.密码加密不正确3.密码已被修改";
    	}else if(a.equals("0")){
    		return "没有需要取得的数据--取用户回复就出现0的返回值,表示没有回复数据";
    	}else{
    		return "未知错误";
    	}
    }
	
	public String toString(String input){
	      input=input.replaceAll("&amp;","&"); 
	      input=input.replaceAll("&apos;","'"); 
	      input=input.replaceAll("&quot;","\""); 
	      input=input.replaceAll("&lt;","<"); 
	      input=input.replaceAll("&gt;",">"); 
	      input=input.replaceAll("&nbsp;"," "); 
	      input=input.replaceAll("<br>","\r\n"); 
	      input=input.replaceAll("<br>","\r"); 
	      input=input.replaceAll(" <br>","\n"); 
	      return input;
	}
	public String sendSMS(String username,String password,String mobile,String contetnt)throws Exception{
		com.ws.util.BS3WebserviceSoap_BindingStub binding;
        try {
            binding = (com.ws.util.BS3WebserviceSoap_BindingStub)
                          new com.ws.util.BS3WebserviceLocator().getBS3WebserviceSoap();
        }
        catch (javax.xml.rpc.ServiceException jre) {
            if(jre.getLinkedCause()!=null)
                jre.getLinkedCause().printStackTrace();
            throw new junit.framework.AssertionFailedError("JAX-RPC ServiceException caught: " + jre);
        }

        // Time out after a minute

        // Test operation
        com.ws.util.SendSMSResponseSendSMSResult value =  binding.sendSMS(username,password,"","","",mobile,contetnt);
        if(value==null){
        	return null;
        }else{
        	MessageElement[] messages=value.get_any();
        	if(messages!=null || messages.length>=1){
        		MessageElement xml= messages[0];
        		return xml.toString();
        	}else{
        		return null;
        	}
        }
        
       	}
	
	public static String[] ReadConfigXml(String url){
        StringReader read = new StringReader(url);  
        //创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入  
        InputSource source = new InputSource(read);  
        //创建一个新的SAXBuilder  
        SAXBuilder sb = new SAXBuilder();  
        try {  
            //通过输入源构造一个Document  
            Document doc = sb.build(source);  
            //取的根元素  
            Element root = doc.getRootElement();  
//            System.out.println(root.getName()+":"+root.getValue());  
              
            List child = root.getChildren();  
            Element e = null;  
            e = (Element)child.get(0);
            log.info(e.getName()+":"+e.getValue()); 
            String a=e.getValue();

            e = (Element)child.get(1);
            log.info(e.getName()+":"+e.getValue()); 
            String b=e.getValue();
            if(b==null){
            	b="";
            }

//            for (int i = 0; i < child.size(); i++){  
//                e = (Element)child.get(i); 
//                System.out.println(e.getName()+":"+e.getValue());  
//            }  
            String abc[]={a,b};
            return abc;
        }catch(JDOMException e){ 
            e.printStackTrace(); 
            String abc[]={"",""};
            return abc;
        }catch(IOException ioe){  
            ioe.printStackTrace();
            String abc[]={"",""};
            return abc;
        }  
	}
	
	
	public void run(){
		log.info("---------------------中视短信接口----------------------------");
		while(flag){
			try{
				log.info("sss:"+times);
				Hz=Integer.parseInt(times);
			}catch(Exception e){
				log.info("错误:"+e);
				log.info("因为获取运行频率出错，改为默认频率1分钟运行");
			}
			log.info("扫描documentout表中未处理的记录："+sql);
			List list=null;
			try{
				list=ftpbean.chaxun(sql);
			}catch(Exception e){
				log.info("获取扫描结果错误："+e);
			}
			if(list!=null){
				for(int i=0;i<list.size();i++){
					Map map=(Map)list.get(i); 
					String StringFrield2=Util.filterForObject(map.get("StringFrield2"));
					String mobile=Util.filterForObject(map.get("DocumentTo"));
					String DocumentPath=Util.filterForObject(map.get("DocumentPath"));
					String TrialCountLimit=Util.filterForObject(map.get("TrialCountLimit"));
					String DocumentOut_GUID=Util.filterForObject(map.get("DocumentOut_GUID"));
					
					if(1==1){
						if(1==1){
							String line="";
//							try{
//								DocumentPath=URLEncoder.encode(DocumentPath,"GB2312");
//							}catch(Exception e){
//								 log.info("DocumentPath转码错误："+e);
//							}
//							log.info("DocumentPath转码："+DocumentPath);
							
						   try {
								line=sendSMS(username,password,mobile,DocumentPath);
							} catch (Exception e1) {
								// TODO Auto-generated catch block
								log.info("发送出错:"+e1);
							}
							
							log.info("返回结果1:"+line);
							line=toString(line);
							log.info("返回结果2:"+line);
							String abc[]=ReadConfigXml(line);
							log.info("返回结果3_1:"+abc[0]);
							log.info("返回结果3_2:"+abc[1]);
								if(abc[0].equals("1")){
									update_sql=" update DocumentOut set Status=1,TrialCount=TrialCount+1,LastTryDateTime='"+LastTryDateTime+"',FinishDateTime='"+FinishDateTime+"',ModifiedDate=sysdate where DocumentOut_GUID='"+DocumentOut_GUID+"'";
									
								}else{
									update_sql=" update DocumentOut set FailCode="+abc[1]+",FailDescription='"+abc[1]+"',Status=5,TrialCount=TrialCount+1,LastTryDateTime='"+LastTryDateTime+"',FinishDateTime='"+FinishDateTime+"',ModifiedDate=sysdate where DocumentOut_GUID='"+DocumentOut_GUID+"'";
								}
								log.info("update_sql:"+update_sql);
								try{
									int a=ftpbean.update(update_sql);
									log.info("是否更新DocumentOut成功:"+a);
								}catch(Exception e){
									log.info("更新DocumentOut出错:"+e);
								}
								
							}else{
								log.info("DocumentOut查询无结果");
							}

							
						}else{
							log.info("手机号"+mobile+"StringFrield2字段错误");
						}
						
					}
				}else{
					log.info("无需要发送的短信");
				}
				
		
                
			try {
				log.info("Hz:"+Hz);
				Thread.sleep(Hz*1000); 
				} 
				catch (Exception e) {
					log.info("定时错误:"+e);
					} 
	}
		}
	}

	























